package com.rui.study.micro.gateway.global;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.ServerWebExchangeDecorator;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @program: study
 * @description:
 * @author: Yaowr
 * @create: 2019-02-19 15:41
 **/
@Component
public class GitWebHooksFilter implements WebFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(GitWebHooksFilter.class);

    private static final String BUS_REFRESH_URI = "/actuator/bus-refresh";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String requestUri = exchange.getRequest().getURI().getPath();
        if (BUS_REFRESH_URI.equals(requestUri)) {
            LOGGER.info("Git web hook !");
            ServerHttpRequest decoratorRequest = new GitWebHookServerHttpRequestDecorator(exchange.getRequest());

            exchange = new GitWebHookServerWebExchange(exchange, decoratorRequest);
        }
        return chain.filter(exchange);
    }

    class GitWebHookServerWebExchange extends ServerWebExchangeDecorator {

        ServerHttpRequest decoratorRequest;

        GitWebHookServerWebExchange(ServerWebExchange delegate, ServerHttpRequest decoratorRequest) {
            super(delegate);
            this.decoratorRequest = decoratorRequest;
        }

        @Override
        public ServerHttpRequest getRequest() {
            return this.decoratorRequest;
        }
    }

    class GitWebHookServerHttpRequestDecorator extends ServerHttpRequestDecorator {

        public GitWebHookServerHttpRequestDecorator(ServerHttpRequest delegate) {
            super(delegate);
        }

        @Override
        public Flux<DataBuffer> getBody() {
            return Flux.empty();
        }
    }
}
